package com.appkubes.fintech.restful.application.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.appkubes.fintech.core.po.FintechCredit;
import com.appkubes.fintech.core.po.FintechCreditExample;
import com.appkubes.fintech.core.po.FintechUserBaseInfo;
import com.appkubes.fintech.restful.application.credit.dao.CreditDao;
import com.appkubes.fintech.restful.application.mall.service.MallService;
import com.appkubes.fintech.restful.application.user.dao.UserBaseInfoDao;
import com.appkubes.fintech.restful.application.user.domain.UserCertificateDomain;
import com.appkubes.fintech.restful.application.user.entity.vo.UserBaseInfoVO;
import com.appkubes.fintech.restful.application.user.service.UserBaseInfoService;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Rongjie
 * @since 2020-01-04
 */
@Service
@Data
public class UserBaseInfoServiceImpl implements UserBaseInfoService {

    @Autowired
    UserBaseInfoDao userBaseInfoDao;

    @Resource
    UserCertificateDomain certificateService; //认证服务

    @Resource
    MallService mallService;


    @Autowired
    CreditDao creditDao;


    /**
     * 基本信息认证
     *
     * @param userBaseInfoVO
     * @return
     */
    @Override
    @Transactional
    public Integer baseInfoCertificate(UserBaseInfoVO userBaseInfoVO) {
        FintechUserBaseInfo userBaseInfo = userBaseInfoDao.selectByPrimaryKey(userBaseInfoVO.getUserKey());
        Integer effectRow = 0;
        if (userBaseInfo == null) {
            //补偿基础数据
            userBaseInfo = new FintechUserBaseInfo();
            BeanUtils.copyProperties(userBaseInfoVO, userBaseInfo);

            JSONObject data = mallService.getUserHierarchyData(userBaseInfoVO.getUserKey());

            //经纪人信息
            userBaseInfo.setRefUserId(data.getString("parent_user_key"));
            userBaseInfo.setRefUserName(data.getString("parent_user_name"));
            userBaseInfo.setRefUserPhone(data.getString("parent_tel"));

            //推广员信息
            userBaseInfo.setRefChannelId(data.getString("promoter_key"));
            userBaseInfo.setRefChannelName(data.getString("promoter_name"));

            //设备信息
            userBaseInfo.setUserSource(data.getString("utm_source"));
            userBaseInfo.setUserDevice(data.getString("platform_type"));

            userBaseInfo.setUpdateTime(new Date());
            userBaseInfo.setCreateTime(new Date());
            effectRow += userBaseInfoDao.insertSelective(userBaseInfo);
        }

        BeanUtils.copyProperties(userBaseInfoVO, userBaseInfo);

        int age = cacAge(userBaseInfoVO.getIdentityNum());
        userBaseInfo.setAge(age);

        userBaseInfo.setUpdateTime(new Date());
        effectRow += userBaseInfoDao.updateByPrimaryKey(userBaseInfo);

        effectRow += certificateService.updateBaseInfoCertificate(userBaseInfoVO.getUserKey(), 1);
        //1,年龄准入规则设置
        if (userBaseInfo.getAge() < 20 || userBaseInfo.getAge() > 50) {
            rejectUser(userBaseInfoVO.getUserKey(), "自动拒绝--命中：年龄准入规则设置，实际年龄：" + userBaseInfo.getAge());
        }
        //2.居住地址规则设置
        if (!userBaseInfo.getLivingProvince().contains("上海")) {
            rejectUser(userBaseInfoVO.getUserKey(), "自动拒绝--命中：居住地准入规则设置，实际居住地：" + userBaseInfo.getLivingProvince());
        }
        //如果存储相关信息，则保存汇总信息
        return effectRow;
    }

    public int cacAge(String idNum) {
        int age = 0;
        if (idNum == null || "".equals(idNum)) {
            return age;
        }
        if (idNum.length() != 15 && idNum.length() != 18) {
            return age;
        }

        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayNow = cal.get(Calendar.DATE);

        try {
            int year = Integer.valueOf(idNum.substring(6, 10));
            int month = Integer.valueOf(idNum.substring(10, 12));
            int day = Integer.valueOf(idNum.substring(12, 14));

            if ((month < monthNow) || (month == monthNow && day <= dayNow)) {
                age = yearNow - year;
            } else {
                age = yearNow - year - 1;
            }
        } catch (Exception e) {
            return age;
        }
        return age;
    }

    public FintechCredit rejectUser(String userKey, String rejectReason) {
        FintechCreditExample example = new FintechCreditExample();
        example.createCriteria().andUserKeyEqualTo(userKey);
        List<FintechCredit> creditList = creditDao.selectByExample(example);
        FintechCredit credit = creditList.get(0);
        credit.setCreditStatus(2);
        credit.setUpdateTime(new Date());
        credit.setApproval(rejectReason);
        creditDao.updateByPrimaryKey(credit);
        return credit;
    }
}
